package com.dj.uphome.web.filter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.parser.Feature;

public class ParamRequest extends HttpServletRequestWrapper {
	private HttpServletRequest request;
	private Map<String,Object> map;
	protected Logger logger = LoggerFactory.getLogger(ParamRequest.class);
	public ParamRequest(HttpServletRequest request) {
		super(request);
		this.request = request;
		map = getBody();
	}
	public Map<String, Object> getMap() {
		return map;
	}

	public void setMap(Map<String, Object> map) {
		this.map = map;
	}

	@Override
	public String getParameter(String name) {
		if (name.equals("req_head")) {
			return request.getParameter(name);
		}
		String json = super.getParameter("req_data");
		if (StringUtils.isEmpty(json)) {
			if(null!=map){
				JSONObject json0 = (JSONObject)map.get("req_data");
				if(null!=json0){
					json = JSONObject.toJSONString(json0);
				}
			}
		}
		if (!StringUtils.isEmpty(json)) {
			JSONObject js = JSONObject.parseObject(json);
			if (null != js) {
				String s = js.getString(name);
				return s;
			}
		}
		return null;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Map getParameterMap() {
		Map<String, String> map2 = new HashMap<String, String>();
		// 遍历map,处理请求
		if (null != map) {
			for (Map.Entry<String, Object> entry : map.entrySet()) {
				if (StringUtils.equals("req_data", entry.getKey())) {
					Object ss = entry.getValue();
					if (null != ss ) {
						JSONObject js = (JSONObject)ss;
						if (null != js) {
							for (Map.Entry<String, Object> entry0 : js.entrySet()) {
								if(null!=entry0.getValue()){
									map2.put(entry0.getKey(), String.valueOf(entry0.getValue()));
								}
							}
						}
					}
				}
	
			}
		}
		return map2;
	}

	@Override
	public String[] getParameterValues(String name) {
		if (name.equals("req_head")) {
			return request.getParameterValues(name);
		}
		String json = super.getParameter("req_data");
		if (StringUtils.isEmpty(json)) {
			if(null!=map){
				JSONObject json0 = (JSONObject)map.get("req_data");
				if(null!=json0){
					json = JSONObject.toJSONString(json0);
				}
			}
		}
		if (!StringUtils.isEmpty(json)) {
			JSONObject js = JSONObject.parseObject(json);
			if (null != js) {
				String s = js.getString(name);
				return new String[] { s };
			}
		}
		return null;
	}

	public  Map<String,Object> getBody(){
	    String body = null;
	    StringBuilder stringBuilder = new StringBuilder();
	    BufferedReader bufferedReader = null;
	    try {
	        InputStream inputStream = request.getInputStream();
	        if (inputStream != null) {
	            bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
	            char[] charBuffer = new char[128];
	            int bytesRead = -1;
	            while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
	                stringBuilder.append(charBuffer, 0, bytesRead);
	            }
	        } else {
	            stringBuilder.append("");
	        }
	    } catch (IOException ex) {
	    } finally {
	        if (bufferedReader != null) {
	            try {
	                bufferedReader.close();
	            } catch (IOException ex) {
	            }
	        }
	    }

	    body = stringBuilder.toString();
	    if(!StringUtils.isEmpty(body)){
	    	try{
	    		LinkedHashMap<String, Object> parseObject = JSONObject.parseObject(body,new TypeReference<LinkedHashMap<String, Object>>(){} ,Feature.OrderedField);
	        	return new JSONObject(parseObject);
	    	}catch(Exception e){
	    		e.printStackTrace();
	    	}
	    }
	    return null;
	}

}
